package com.sinoyd.itszyw.Activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.sinoyd.itszyw.Dialog.DownloadDialog;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * @author: Sinoyd  --------->作者
 * @description: --------->描述
 * @projectName: ITSZYW  ---------> 项目名称
 * @date: 2017-03-09 ---------> 创建日期
 * @time: 09:02       ---------> 创建时间
 */
public class BaseActivity extends AppCompatActivity implements DownloadDialog.DownloadListener{
    public static Toast mToast;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }


    /**
     * @param params      请求参数
     * @param method      请求方法
     * @param requestCode 请求代码标识
     * @throws Exception
     */
    public void sendHttpRequest(RequestParams params,
                                HttpMethod method, int requestCode)
            throws Exception {
        final int code = requestCode;

//        params.setCacheMaxAge(1000*0); //为请求添加缓存时间
//        params.setConnectTimeout(60); //超时时间60s

        params.setConnectTimeout(1 * 1000);// 连接超时  //指的是连接一个url的连接等待时间。
        x.http().request(method, params, new Callback.ProgressCallback<String>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                httpOnLoading(total,current);

            }

            @Override
            public void onSuccess(String result) {
                httpOnSuccess(result, code);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    showToast(responseMsg + errorResult + responseCode);
                } else { // 其他错误
                    Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }


            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    public void httpOnSuccess(String responseStr, int requestCode) {

    }
    public void httpOnLoading(long total, long current){

    }

    /**
     * 返回键
     */
    public void goBack() {
        new Thread() {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    Log.e("sendKeyDownUpSync error", e.toString());
                }
            }
        }.start();
    }


    /**
     * 吐司
     */
    public void showToast(String msg) {

        if (mToast == null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);

        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    /**
     * 点击隐藏 键盘
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }



    @Override
    public void startDownload() {

    }

    @Override
    public void endDownload(String filePath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + Environment.getExternalStorageDirectory()
                        + "/DownLoadApp/ITYW.apk"),
                "application/vnd.android.package-archive");
        startActivity(intent);
        System.exit(0);


    }
}
